2017-12-29 1 views
-1

H 모두,C++는, 추상 클래스 속성을

내가 확장 된 추상 클래스의 게터/세터를 생성하고 보호받을 수 없다, 이해가 안 돼요 세터.

// 홈페이지 파일

#include <iostream> 
#include "cat.h" 
int main() { 
    Cat* tom; 
    tom->setName("TOM"); 
    std::cout << tom->getName() << std::endl; // Here I got error EXC_BAD_ACCESS (code=EXC_I386_GPFLT) 
    return 0; 
} 

//Animal.h 파일

#ifndef CLASSES_ANIMAL 
#define CLASSES_ANIMAL 

#include <string> 

using namespace std; 
class Animal { 
    protected: 
    string name; 
    public: 
    virtual inline string getName() const = 0; 
    virtual void setName() = 0; 
    virtual ~Animal() = default; 
}; 

#endif //CLASSES_ANIMAL 

// Cat.h

에서
#ifndef CLASSES_CAT_H 
#define CLASSES_CAT_H 

#include <string> 
#include "animal.h" 

class Cat : protected Animal { 
    public: 
    Cat(){}; 
    inline string getName() const{ return name; } 
    void setName(string sentName); 
    ~Cat(){}; 
}; 


#endif //CLASSES_CAT_H 

// Cat.cpp

#include "cat.h" 

void Cat::setName(string sentName) { 
    if(!sentName.empty()){ 
    name = sentName; 
    } 
} 
+1

_instantiation? _ 또는 포인터 만? – snr

+4

포인터 'tom'이 초기화되지 않았습니다. Dereferencing'tom'은 정의되지 않은 행동을합니다 (여러분의 경우 충돌). 개체를 초기화해야합니다 (예 : 'auto tom = std :: make_unique ();' – 0x5453

+1

초기화되지 않은 지역 변수는 * 불확정 * 값을가집니다 (거의 무작위로 보일 것입니다). 이제 포인터 변수'tom'을 역 참조 할 때 어떤 일이 일어날 지 생각해보십시오. –

답변

2

개체를 만들어야합니다.

Cat* tom = new Cat(); 
+1

원시'new' 사용을 주장하는 경우 메모리 누수를 피하기 위해'delete'도 호출해야합니다. 더 나은 방법으로, 새로 생성/삭제 대신 [스마트 포인터] (https://en.wikipedia.org/wiki/Smart_pointer)를 사용하십시오. – 0x5453

+0

Hum ... 컴파일러가 ""Cat을 추상 클래스 유형의 객체로 할당 " 실제로 클래스를 확장하려고합니다 (추상 클래스 확장) & 액세스가 보호 된 속성 상위 클래스의 – nodeover

+0

나는 그가 소멸자를 작성했다고 생각한다. @ 0x5453 – snr