我尝试了不同的版本调用构造函数,我想出了这个分配初始化
#include<iostream>
#include<string>
using namespace std;
class game{
public:
float version;
string name;
game()
{
name = "game";
version = 1.0;
}
game(float v,string n)
{
version = v;
name = n;
}
game(float v)
{
version = v;
name="any";
}
};
int main()
{
game lol1(1.0,"league of legends"); //functional form
game lol2 = 2.0; //assignment form
game lol3{3.0,"league2"}; //uniform initialization
game *pt = &lol1;
cout<<pt->name<<endl;
return 0;
}
每个语句编译,但如果我写
game lol2 = 2.0,"league of legends2"; //code 2
我得到一个错误:
expected unqualified-id before string constant
但下面的代码工作正常:
game lol2 = {2.0,"league of legends2"}; //code 3
我不明白第二个代码到底是什么问题。有任何想法吗?
您可以使用默认参数将构造函数压缩为单个构造函数。 –
为了娱乐,添加一个构造函数,只需要一个字符串.... –