Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何初始化对象_C++_Object_Initialization - Fatal编程技术网

C++ 如何初始化对象

C++ 如何初始化对象,c++,object,initialization,C++,Object,Initialization,关键是初始化一个指向神秘对象的指针,其值为“beep”有什么想法吗 class Mystic { private: string label; Mystic(string & newlbl) { setLabel (newlbl)}; public: void setLabel(string newlbl){label = newlbl;} Mystic() : label(){}; }; int main(int argc, char *argv[]) { ... //

关键是初始化一个指向神秘对象的指针,其值为“beep”有什么想法吗

class Mystic { 
private:
 string label;
 Mystic(string & newlbl) { setLabel (newlbl)};
public:
 void setLabel(string newlbl){label = newlbl;}
 Mystic() : label(){};
};
int main(int argc, char *argv[])
{
...    //i tried this
       //string *p1 = new string("beep");
      //Mystic myst(p1);
} 

接受字符串的构造函数不是公共的,因此不能使用它。而是使用默认构造函数,然后使用setLabel方法

int main(int argc, char** argv) {
  Mystic m;
  m.setLabel("beep");
  Mystic* p = &m;
}

您试图使用的构造函数是私有的,您只能访问公共的,所以您必须将该构造函数设置为公共的,或者如果您想使用公共默认构造函数并初始化默认值
Mystic():label(“default”){}

,因为这个问题涉及混淆指针和引用,并显示一些反模式,最好用一本好的C++书来回答这个问题。也许你应该看一看。