没有构造函数参数的类在标题和源分离时无法编译

时间:2017-05-19 19:53:15

标签: c++

我尝试了两种创建类的方法。

1)在与main.cpp相同的文件中创建类,并在与main相同的文件中定义类的成员函数。

2)在单独的(.h)文件中创建类,并在单独的(.cpp)源文件中定义类的成员函数。当我做1)一切都按预期工作。当我这样做2)我不能使用该类而不将初始值传递给构造函数,(默认构造函数)参数似乎不初始化代码或其他东西。我真的很困惑,为什么它在2)中不起作用,但它适用于1)它们应该做同样的事情。

1)main.cpp

#include <iostream>
using namespace std;

class Dog {
public:
    Dog();
    ~Dog();
    int years_old;
};
Dog::Dog() {
    years_old = 10;
    std::cout << "we are inside dog constructor" << std::endl;
}
Dog::~Dog() {}

int main() {
    Dog dogg;
    cout << "Dog is: " << dogg.years_old << "years old!" << endl;
    cout << "We are in main" << endl;
    return 0;
}

2) Dog.h:

#ifndef DOG_H
#define DOG_H
class Dog {
public:
    Dog(); // if I pass in arguments both here and in main and in Dog.cpp this works
    ~Dog();
    int years_old;
};
#endif

2)Dog.cpp

#include <iostream>
#include "Dog.h"

Dog::Dog() {
    years_old = 10;
    std::cout << "we are inside dog constructor" << std::endl;
};
Dog::~Dog() {
};

2)main.cpp

#include <iostream>
#include "Dog.h"
using namespace std;

int main() {
    Dog dogg;
    cout << "Dog is: " << dogg.years_old << "years old!" << endl;
    cout << "We are in main" << endl;
    return 0;
}

我收到此错误:

Undefined symbols for architecture x86_64:
  "Dog::Dog()", referenced from:
      _main in main-ddbb4d.o
  "Dog::~Dog()", referenced from:
      _main in main-ddbb4d.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

0 个答案:

没有答案