当我尝试创建一个类的数组时,我遇到了一个错误,所以我开始在类中删除变量。我发现删除名为vector2
的所有结构,编译器将能够创建该类的数组。我不知道为什么它不起作用,或者为什么结构会影响它。
#include <iostream>
using namespace std;
struct vector2
{
double x = 0, y = 0;
vector2(double doubleX, double doubleY)
{
x = doubleX;
y = doubleY;
}
};
class Dog
{
private:
vector2 location;
int age;
public:
void setLocation(vector2);
vector2 getLocation();
void setAge(int);
int getAge();
};
void Dog::setLocation(vector2 newLocation)
{
location = newLocation;
}
vector2 Dog::getLocation()
{
return location;
}
void Dog::setAge(int newAge)
{
age = newAge;
}
int Dog::getAge()
{
return age;
}
int main()
{
Dog myDogs[1];
myDogs[0].setAge(10);
return 0;
}
顺便说一句:我注意到一些vector2
代码不起作用,但我使用std::vector
尝试了这一点,并且它完美地工作(使用构造函数)
答案 0 :(得分:0)
您的Dog
有一个vector2
成员变量,但vector2
没有默认构造函数。并且您没有使用Dog
的参数化构造函数的vector2
构造函数。
给vector2
一个默认构造函数
vector2::vector2() : x{0.0}, y{0.0} {}
或者Dog
的构造函数使用vector2
的参数化构造函数
Dog::Dog(int _age) : age{_age}, location{0.0, 0.0} {}