저는 최근 Java 및 기타 고급 언어의 배경에서 오는 C ++를 배우기 위해 노력하고 있습니다. 포인터와 개체에 몇 가지 문제가 있었지만 포인터를 사용하여 사용자 지정 클래스로 만든 개체를 조작하는 방법을 정확하게 설명하는 좋은 리소스를 아직 찾지 못했습니다.
내 문제가있는 곳을 좁히기 위해 간단한 프로그램을 작성했습니다.
이 클래스의 맨 아래에있는 코드의 마지막 두 블록은 잘못되었으며 다른 부분에서도 몇 가지 잘못된 작업을 수행했을 것입니다. 도움을 주시면 감사하겠습니다.
#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
class Point {
public:
float x;
float y;
public:
Point(float x, float y) {
this->x=x;
this->y=y;
}
Point() {
x=0.0f;
y=0.0f;
}
~Point() {
x=0.0f;
y=0.0f;
}
};
class Place {
public:
string name;
Point location;
public:
//Constructor with arguements.
Place(string nam, Point loc) {
name = nam;
location = loc;
}
//Default constructor.
Place() {
name = "Default";
location = {0.0f,0.0f};
}
//Destructor. This object contains no pointers so nothing to delete.
~Place() {
}
public:
void setName(string nam) {
name = nam;
}
void setLocation(Point loc) {
location = loc;
}
};
class PointerToAPlace {
public:
Place *place;
public:
PointerToAPlace(Place *pl) {
*place = *pl;
}
~PointerToAPlace() {
delete place;
}
};
int main(int argc, char** argv) {
std::cout << "\n";
std::cout << "Make some places and hope they don't segfault.\n";
/*Object created with default constructor. Will be automatically deleted at the end of this scope.*/
Place placeA;
std::cout << "Place named " << placeA.name.c_str() << " is at " << placeA.location.x << "," << placeA.location.y << " and is lovely.\n";
//Output: Place named Default is at 0,0 and is lovely.
/*Object created with bracket constructor. Will be automatically deleted at the end of this scope.*/
Place placeB = {"Lordran", Point{12.2f,99.3f}};
std::cout << "Place named " << placeB.name.c_str() << " is at " << placeB.location.x << "," << placeB.location.y << " and is lovely.\n";
//Output: Place named Lordran is at 12.2,99.3 and is lovely.
/*Object created with new keyword. This is a pointer and must be explicitly deleted.*/
Place *placeC = new Place("Drangleic", Point{-123.34f,69.69f});
std::cout << "Place named " << placeC->name.c_str() << " is at " << placeC->location.x << "," << placeC->location.y << " and is lovely.\n";
delete placeC;
//Output: Place named Drangleic is at -123.34,69.69 and is lovely.
/*Array of objects, created with default constructor and not assigned any values. Will be automatically deleted at the end of this scope.*/
Place placeD[3];
std::cout << "Here are some places named: ";
for(int i=0;i<3;i++) {
std::cout << placeD[i].name.c_str();
std::cout << (i<2 ? ", " : ". ");
}
std::cout << "They are quite the places!\n";
//Output: Here are some places named: Default, Default, Default. They are quite the places!
/*Array of objects, created with default constructor and then assigned values. Will be automatically deleted at the end of this scope.*/
Place placeE[5];
string namesA[5] = {"Boletaria", "Stonefang", "Latria", "Shrine of Storms", "Valley of Defilement"};
for(int i=0;i<5;i++) {
placeE[i].setName(namesA[i]);
placeE[i].setLocation(Point{1.23f, 3.21f});
}
std::cout << "Here are some places named: ";
for(int i=0;i<5;i++) {
std::cout << placeE[i].name.c_str();
std::cout << (i<4 ? ", " : ". ");
}
std::cout << "They are quite the places!\n";
//Output: Here are some places named: Boletaria, Stonefang, Latria, Shrine of Storms, Valley of Defilement. They are quite the places!
/*Trying to do a pointer to an array of objects.*/
Place *placeF[7];
string namesB[7] = {"Astora", "Carim", "Thoroughland", "Catarina", "Baulder", "Vinheim", "Zena"};
for(int i=0;i<7;i++) {
placeF[i]->setName(namesB[i]);
placeF[i]->setLocation(Point{2.23f, 6.21f});
}
std::cout << "Here are some places named: ";
for(int i=0;i<7;i++) {
std::cout << placeF[i]->name.c_str();
std::cout << (i<6 ? ", " : ". ");
}
std::cout << "They are quite the places!\n";
//Output: SEGFAULT D:
/*Trying to put a pointer to a place into an object, then delete it.*/
Place *placeG = new Place("Anor Londo", Point{-12312.34f,33.69f});
PointerToAPlace pnt = {placeG};
std::cout << "Place named " << pnt.place->name.c_str() << " is at " << pnt.place->location.x << "," << pnt.place->location.y << " and is lovely.\n";
//Output: SEGFAULT :(
return 0;
}
PointerToAPlace(Place *pl) {
*place = *pl;
}
이것은 잘못된 것입니다. 당신이하려는 것이 포인터를 저장하는 것이라면 다음과 같이하십시오.
PointerToAPlace(Place* pl) {
place = pl;
}
또는 더 나은 방법은 생성자 이니셜 라이저 목록을 사용하는 것입니다.
PointerToAPlace(Place* pl) : place(p1) {
}
현재 코드가 설정되지 않았 place
으므로 누가 어디를 아는지를 가리키는 정크 값을 포함하고이를 역 참조합니다 (정의되지 않은 동작).
또한 복사 할 때주의해야합니다 PointerToAPlace
. 현재 복사하면 두 개체가 모두 동일한 포인터를 보유하고 있으며 둘 다 삭제를 시도합니다.
어떻게 구문의 작동 및 사용 방법 배운 후에는 이럴 new
/ delete
당신이 그들을 사용을 중지하고 대신 스마트 포인터를 사용해야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다