求帮助们一个问题。假如类class A里有构造函数A(){} 主函数中 A a; 这样设置对象为什么会报错…
码拜
求帮助高手们一个问题。假如类class A里有构造函数A(){}
主函数中
A a;
这样设置对象为什么会报错…
假如重载了函数模版想在其他函数里而不是主函数中初始化成员应该怎么办呢。
#include <iostream>
using namespace std;
class Test{
private:
int a;
int b;
char c;
public:
Test(int ax, int bx){
a = ax;
b = bx;
}
Test(char cx):c(cx){
}
void Print(){
cout << a <<” “<<b;
}
};
int main(){
Test t;
t.Print();
return 0;
}
Untitled.cpp:32:7: error: no matching constructor for initialization of “Test”
Test t;
^
Untitled.cpp:19:3: note: candidate constructor not viable: requires single argument “cx”, but no arguments were provided
Test(char cx):c(cx)
^
Untitled.cpp:5:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class Test{
^
Untitled.cpp:14:3: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
Test(int ax, int bx){
^
1 error generated.
这是一个实验函数和它的报错。
但是本人再另一个程序中却没有报错 class Pet
{
public:
/*******构造类函数********/
//构造函数模版(sex,colour,weight)
Pet(string sex, string colour, string weight)
{
PetSex = sex;
PetColour = colour;
PetWeight = weight;
}
//重载成员列表初始化构造函数
Pet(int hun, int thir ,int mood , int heal , int clean)
:StateHungry(hun),StateMood(mood),StateHealth(heal),StateClean(clean)
{
}
…//其他成员函数
};
int main()
{ Pet p;
//PrintHomePage(p);
//BreedManual();
return 0;
}
这样就没有报错。
希望各位高手可以帮忙解答一下。蟹蟹蟹蟹喵> <
就是例如说
class Test{
private:
int a;
int b;
char c;
public:
Test(int al,intbl){
a = al;
b = bl;
}
Test(char cl){
c = cl;
}
};
void main(){
Test t(2,1);
Test t(“A”);
}
这样写对嘛?
不对,你构造的两个类对象重名了,以下是对的:
class Test{
private:
int a;
int b;
char c;
public:
Test(int al,int bl){
a = al;
b = bl;
}
Test(char cl){
c = cl;
}
};
void main(){
Test t1(2,1);
Test t2("A");
}