0

3 файла:

main.cpp

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

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

animal.h

#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>

using namespace std;
class Animal
{
protected:
    string _name;
    int _age;
    bool _isMan;
    static int _totalAnimal;
public:
    Animal();
    Animal(string name, int age, bool isMan);
    Animal(const Animal & obj); // конструктор копирования
    ~Animal();
    void setName(string name);
    void setAge(int _age);
    void setMan(bool _isMan);
    string getName() const;
    int getAge() const;
    bool getMan() const;
    static int totalAnimal();
    virtual string get_type() const = 0;
    friend ostream& operator<<(ostream& os, const Animal& dt);
};
int Animal::_totalAnimal = 10;

#endif // ANIMAL_H

animal.cpp

#include "animal.h"


Animal::Animal() { Animal::_totalAnimal++; }
Animal::Animal(string name, int age, bool isMan) {
    Animal::_totalAnimal++;
    setName(name);
    setAge(age);
    setMan(isMan);
}
Animal::Animal(const Animal & obj) {
    _name = obj._name;
    _age = obj._age;
    _isMan = obj._isMan;
}
Animal::~Animal() {
    Animal::_totalAnimal--;
}
void Animal::setName(string name) {
    if (name != "")
        _name = name;
    else
        throw 1;
}
void Animal::setAge(int age) {
    if (age >= 0)
        _age = age;
    else
        throw 2;
}
void Animal::setMan(bool isMan) {
    _isMan = isMan;
}
string Animal::getName() const { return _name; }
int Animal::getAge() const { return _age; }
bool Animal::getMan() const { return _isMan; }
int Animal::totalAnimal() { return Animal::_totalAnimal; }

Выдает 3 ошибки:

C:\Users\q\Documents\QT Project\pesok\animal.cpp:-1: ошибка: multiple definition of `Animal::_totalAnimal'
C:\Users\q\Documents\QT Project\pesok\main.cpp:-1: first defined here
collect2.exe:-1: ошибка: error: ld returned 1 exit status

Еще кому интересно pro-файл в проекте QT:

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp \
    animal.cpp

HEADERS += \
    animal.h

1 ответ 1

2

Вот это вот определение

int Animal::_totalAnimal = 10;

у вас находится в h-файле, который включается в два .cpp-файла и, таким образм, вы имеете два определения одного и того же статического члена, и, соответственно, нарушение правила одного определения.

Перенесите его в один (и только в один) .cpp-файл.

Если у вас С++17, можно также определить статический член прямо в классе с использованием ключевого слова inline.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.