2009-05-14 3 views
32

저는 C++ 클래스에 대한 많은 자습서를 읽었지 만 다른 자습서에 포함 된 것을 놓치고 있습니다.C++에서 간단한 클래스를 작성하는 방법은 무엇입니까?

누군가 가시성, 메소드 및 간단한 생성자와 소멸자를 사용하는 매우 간단한 C++ 클래스를 작성하고 사용하는 방법을 보여줄 수 있습니까?

+30

이것은 숙제입니다! – xian

+7

나는 그 주제에 대한 인터넷 검색을 통해 어떤 예도 찾을 수 없다고 거의 믿을 수 없다. 아래 예제의 대부분은 다른 웹 튜토리얼에서 복사하여 여기에 붙여 넣습니다. –

+7

당신은 심각하게 열심히 보지 말았어야합니다. –

답변

8
class A 
{ 
    public: 
    // a simple constructor, anyone can see this 
    A() {} 
    protected: 
    // a simple destructor. This class can only be deleted by objects that are derived from this class 
    // probably also you will be unable to allocate an instance of this on the stack 
    // the destructor is virtual, so this class is OK to be used as a base class 
    virtual ~A() {} 
    private: 
    // a function that cannot be seen by anything outside this class 
    void foo() {} 
}; 
25

음은 촬영 예를 문서화하고 Constructors and Destructors in C++에서 더 나은 설명 :

#include <iostream>   // for cout and cin 

class Cat      // begin declaration of the class 
{ 
    public:      // begin public section 
    Cat(int initialAge);  // constructor 
    Cat(const Cat& copy_from); //copy constructor 
    Cat& operator=(const Cat& copy_from); //copy assignment 
    ~Cat();     // destructor 

    int GetAge() const;  // accessor function 
    void SetAge(int age);  // accessor function 
    void Meow(); 
private:      // begin private section 
    int itsAge;    // member variable 
    char * string; 
}; 

// constructor of Cat, 
Cat::Cat(int initialAge) 
{ 
    itsAge = initialAge; 
    string = new char[10](); 
} 

//copy constructor for making a new copy of a Cat 
Cat::Cat(const Cat& copy_from) { 
    itsAge = copy_from.itsAge; 
    string = new char[10](); 
    std::copy(copy_from.string+0, copy_from.string+10, string); 
} 

//copy assignment for assigning a value from one Cat to another 
Cat& Cat::operator=(const Cat& copy_from) { 
    itsAge = copy_from.itsAge; 
    std::copy(copy_from.string+0, copy_from.string+10, string); 
} 

// destructor, just an example 
Cat::~Cat() 
{ 
    delete[] string; 
} 

// GetAge, Public accessor function 
// returns value of itsAge member 
int Cat::GetAge() const 
{ 
    return itsAge; 
} 

// Definition of SetAge, public 
// accessor function 
void Cat::SetAge(int age) 
{ 
    // set member variable its age to 
    // value passed in by parameter age 
    itsAge = age; 
} 

// definition of Meow method 
// returns: void 
// parameters: None 
// action: Prints "meow" to screen 
void Cat::Meow() 
{ 
    cout << "Meow.\n"; 
} 

// create a cat, set its age, have it 
// meow, tell us its age, then meow again. 
int main() 
{ 
    int Age; 
    cout<<"How old is Frisky? "; 
    cin>>Age; 
    Cat Frisky(Age); 
    Frisky.Meow(); 
    cout << "Frisky is a cat who is " ; 
    cout << Frisky.GetAge() << " years old.\n"; 
    Frisky.Meow(); 
    Age++; 
    Frisky.SetAge(Age); 
    cout << "Now Frisky is " ; 
    cout << Frisky.GetAge() << " years old.\n"; 
    return 0; 
} 
+2

싫어하십시오 get/set here. 고양이 남용을 허용합니다. 연령을 설정할 수 없어야합니다 (연령이 낮아질 수 있음)하지만 나이를 늘릴 수 있어야합니다. –

+2

아니면 SetBirthday()와 GetAge()가 있어야합니다. – Reunanen

+3

또한 학습 예제로 사용하기 때문에 접근자를 개체의 내용을 변경하지 않으므로 초보자로 표시해야합니다. –

4
#include <iostream> 
#include <string> 

class Simple { 
public: 
    Simple(const std::string& name); 
    void greet(); 
    ~Simple(); 
private: 
    std::string name; 
}; 

Simple::Simple(const std::string& name): name(name) { 
    std::cout << "hello " << name << "!" << std::endl; 
} 

void Simple::greet() { 
    std::cout << "hi there " << name << "!" << std::endl; 
} 

Simple::~Simple() { 
    std::cout << "goodbye " << name << "!" << std::endl; 
} 

int main() 
{ 
    Simple ton("Joe"); 
    ton.greet(); 
    return 0; 
} 

바보, 그러나, 당신은 거기에. 공개 설정과 비공개 제어의 접근성은 '공개 설정'이 잘못된 것임을 유의해야합니다.하지만 '개인 정보'는 외부에서 '볼 수 있음'입니다. 에 액세스 할 수 없습니다.이 설정을 시도하면 오류가 발생합니다.

+0

사실 가시성으로 인해 문제가 발생할 수 있습니다. 컴파일러는 어떤 오버로드 된 함수가 가시성에 기반하여 호출하고 인수에서 가장 잘 일치 하는지를 선택하고 액세스 할 수없는 함수로 마무리합니다. 이러한 개념은 혼란 스러울 수 있습니다. –

+0

Alex가 문자열 이름 대신 문자열 & 이름을 사용하는 이유 – Babiker

+2

"const string & name"은 복사가 수행되지 않는다는 것을 의미하고 "string name"은 컴파일러에게 복사본을 작성하도록 지시합니다. 필요 없는데 왜 사본을 요청합니까? 인수 습관은 좋은 습관입니다. int, 포인터 등의 간단한 값 유형이 아닌 arg를 읽기 전용 방식으로 사용할 때 const를 전달하십시오. –

10

그는, 그것은 단지 한 두 개의 디자인 패러다임의 교차로 역할 ++ 적어도 C에서 C++ :

클래스의 새로운 방문자를 위해 그렇게 쉬운 일이 아니기 때문에 답변을 시도할만한 가치가

학생,하더라도

1) ADT :: 기본적으로 새로운 유형, 정수 'int'또는 실수 'double'또는 'date'와 같은 새로운 개념을 의미합니다. 간단한 클래스는 다음과 같이한다이 경우 ,

class NewDataType 
{ 
public: 
// public area. visible to the 'user' of the new data type. 
. 
. 
. 
private: 
// no one can see anything in this area except you. 
. 
. 
. 
}; 

이 인 ADT의 가장 기본 골격 ... 물론 그것은 공공 영역을 무시하여 간단 할 수 있습니다! 및 액세스 수정 자 (공개, 비공개)를 지우면 모든 것이 비공개가됩니다. 하지만 그저 난센스입니다. NewDataType은 쓸모 없기 때문에! 선언 할 수있는 'int'를 상상해보십시오.하지만 그걸로는 아무 것도 할 수 없습니다.

그런 다음 기본적으로 NewDataType이 필요하지 않은 유용한 도구가 필요하지만 형식을 언어의 기본 유형처럼 보이게하려면 유용한 도구가 필요합니다.

첫 번째 것은 생성자입니다. 생성자는 언어의 여러 위치에서 필요합니다. int를보고 동작을 모방하려고합니다.

int x; // default constructor. 

int y = 5; // copy constructor from a 'literal' or a 'constant value' in simple wrods. 
int z = y; // copy constructor. from anther variable, with or without the sametype. 
int n(z); // ALMOST EXACTLY THE SAME AS THE ABOVE ONE, it isredundant for 'primitive' types, but really needed for the NewDataType. 

위의 라인 중 모든 라인은 선언이며, 변수는 거기서 생성됩니다.

하고 결국

여기 컴파일러 원하는 것을 말할 수
int fun() 
{ 
    int y = 5; 
    int z = y; 
    int m(z); 

    return (m + z + y) 
    // the magical line. 
} 

당신이 마법의 라인을 참조하는 함수 위의 INT 변수는, 그 기능은 '재미'라고 상상! 모든 작업을 수행 한 후에 NewDataType이 함수와 같은 로컬 범위에 유용하지 않으면 Kill It IT가됩니다. 고전적인 예는 'new'가 예약 한 메모리를 해제합니다!

그래서 우리의 매우 간단한 NewDataType는

class NewDataType 
{ 
public: 
// public area. visible to the 'user' of the new data type. 
    NewDataType() 
    { 
     myValue = new int; 
     *myValue = 0; 
    } 

    NewDataType(int newValue) 
    { 
     myValue = new int; 
     *myValue = newValue; 
    } 

    NewDataType(const NewDataType& newValue){ 

     myValue = new int; 
     *myValue = newValue.(*myValue); 
    } 
private: 
// no one can see anything in this area except you. 
    int* myValue; 
}; 

지금이 공공 기능을 제공하는 당신이 유용한 클래스를 구축 시작, 아주 기본 골격이다,이된다.

는 작은 도구의 많은 C++에서 클래스를 구축 고려

있다. . . .

2) Object :: 기본적으로 새로운 유형을 의미하지만, 차이점은 형제, 자매, 조상 및 자손에 속한다는 점입니다. C++에서 'double'과 'int'를 보면, 'int'는 모든 'int'가 적어도 개념상 'double'이기 때문에 'double'의 태양입니다 :

관련 문제