注册 登录
编程论坛 C++教室

求教下构造函数怎么返回一个字符串!能写个例子最好

山桀骜云轻狂 发布于 2015-10-13 19:08, 547 次点击
求教下构造函数怎么返回一个字符串!能写个例子最好
4 回复
#2
hjx11202015-10-13 19:39
https://msdn.
msdn上的例子,好好学习,天天向上,good luck
#3
rjsp2015-10-13 21:01
听不懂在说什么
#4
yangfrancis2015-10-13 22:54
回复 楼主 山桀骜云轻狂
//构造函数没有返回值,也就不能返回字符串了。但可以把字符串作为指针形参传到构造函数中,这样构造完成之后你仍然可以得到一个字符串。
#include<iostream>
#include<stdlib.h>
using std::cin;using std::cout;using std::endl;
class A
{
public:
    A(char*str)
    {
        cout<<"请输入一个字符串:";
        cin>>str;
        strcpy(MyStr,str);
    }
    void ShowString(){cout<<MyStr;}
private:
    char MyStr[50];
};
int main()
{
    char x[]="abc";
    cout<<x<<endl;
    A NewInstance(x);
    cout<<x<<endl;
    NewInstance.ShowString();
    system("pause");
    return 0;
}
#5
kenierlee2015-10-14 10:56
楼主说的可是这个意思?
程序代码:
class X
{
public:
  operator string();
};

X::operator string()
{
  return string("123");
}

int main()
{
  ...
  string str = X();
  ...
}
1