gpt4 book ai didi

c++ - 指向另一个对象的指针

转载 作者:行者123 更新时间:2023-11-28 05:13:01 25 4
gpt4 key购买 nike

我有一个小问题..我想做汽车登记,我想拥有所有者(指向 Person 对象的指针)但是当我想用 get 函数获取所有者时我不能这样做......并且这对我来说是个谜......也许我在某处犯了一个小错误,但我找不到它......请帮忙:)

class Person
{
friend class Cars;
public:
Person(){}
Person(uint8_t age, string name) :m_age(age), m_name(name)
{
m_idGener = s_idGenerator++;
}

int getId()
{
return m_idGener;
}
uint8_t getAge()
{
return m_age;
}
string getName()
{
return m_name;
}
private:
string m_name;
uint8_t m_age;
static int s_idGenerator;
int m_idGener;

};
class Cars:public Person
{

public:
Person *m_owner; // this is my pointer which i want to point to cars Object
it will stay public for the test after the test i will move it in the private section
Cars()
{
}
// getters and setters

Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
{
object.m_owner = &owner;
}
Cars getOwner(Cars &object) /// here is my problem i can't take the owner
{
return *(object.m_owner); // but i can't take the owner
}

uint16_t getHorsePower()
{
return horsePower;
}
string getRegNumber()
{
return registrationNumber;
}
private:
string m_manufacturerName;
string modelName;
uint16_t horsePower;
string registrationNumber;

};

int Person::s_idGenerator = 0;

最佳答案

你犯了更多错误。至少应更正以下内容:

Cars setOwner(Cars &object,  .....

这个方法没有返回值,所以应该是void。 car 对象应该是调用方法的对象,而不是参数。

Cars getOwner(Cars &object) /// here is my problem i can't take the owner 
{
return *(object.m_owner); // but i can't take the owner
}

在这个方法中,我会将返回类型更改为Person *,然后简单地返回m_owner。不需要参数。

修改后的工作示例:

#include <string>
#include <iostream>
using namespace std;
class Person
{
friend class Cars;
public:
Person(){}
Person(uint8_t age, string name) :m_age(age), m_name(name)
{
m_idGener = s_idGenerator++;
}

int getId()
{
return m_idGener;
}
uint8_t getAge()
{
return m_age;
}
string getName()
{
return m_name;
}
private:
string m_name;
uint8_t m_age;
static int s_idGenerator;
int m_idGener;

};
class Cars:public Person
{

public:
Person *m_owner; // this is my pointer which i want to point to cars Object
// it will stay public for the test after the test i will move it in the private section
Cars()
{
}
// getters and setters

void setOwner(Person &owner) // with this function i set the owner
{
m_owner = &owner;
}
Person *getOwner() /// here is my problem i can't take the owner
{
return (m_owner); // but i can't take the owner
}

uint16_t getHorsePower()
{
return horsePower;
}
string getRegNumber()
{
return registrationNumber;
}
private:
string m_manufacturerName;
string modelName;
uint16_t horsePower;
string registrationNumber;

};

int Person::s_idGenerator = 0;

int main() {
Person p(5,"Bill");
Cars c;

c.setOwner(p);
cout << c.getOwner()->getName();
}

关于c++ - 指向另一个对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com