当在数组中使用类时,Struct in Class会出现错误

时间:2015-02-14 19:14:21

标签: c++ arrays struct

当我尝试创建一个类的数组时,我遇到了一个错误,所以我开始在类中删除变量。我发现删除名为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尝试了这一点,并且它完美地工作(使用构造函数)

1 个答案:

答案 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} {}