gpt4 book ai didi

java - 从 Java 到 C++ : how to use one custom class var within another custom class?

转载 作者:太空狗 更新时间:2023-10-29 23:39:47 25 4
gpt4 key购买 nike

假设我在 Java 中有两个自定义类,A 类和 B 类:

class A {
int x;
int y;
public A(int x, int y)
{
this.x = x;
this.y = y;
}
}

class B {
A a;
int z;
public B(A a, int z)
{
this.a = a;
this.z = z;
}
}

我想将这种情况转化为 C++。

A类会按原样翻译或多或少,但是当我去B类写这样的代码时:

class B {
A a;
int z;
public:
B(A a1, int z1){
a = a1;
z =z1;
}
};

它提示说 A 类没有默认构造函数,所以当我声明一个;在 B 类的顶部,它无法实例化我的“a”变量(据我所知,Java 不会在声明时实例化,而 C++ 会实例化)。

那么处理这种情况的正常 C++ 方法是什么:我应该向类 A 添加不带参数的默认构造函数,还是这不是正确的方法?

非常感谢。

最佳答案

从 Java 到 C++ 的转换对上下文非常敏感。它们确实是非常不同的语言,这在很大程度上取决于您要实现的目标。

在 Java 中,用户定义的类型都是通过引用访问的。 C++ 中的功能等价物是指针。但是在 C++ 中,您可以像内置类型一样直接访问对象。所以你可以这样写:

class A {
int x;
int y;

public:
// note: we don't initialize members in the body
A(int x, int y): x(x), y(y) {}
};

class B {
A a;
int z;

public:
B(A a, int z): a(a), z(z) {}
};

C++ 为您提供了更多如何引用用户定义类型的选项,因此这实际上取决于您需要解决的更大问题。

一些其他的可能性:

std::shared_ptr<A> a; // much more Java-like (slower)
std::unique_ptr<A> a; // when you need one copy only (more common)
A* a; // when you need to live dangerously
A a; // use it more like a built-in

引用资料:

std::unique_ptr当你只需要管理一个

std::shared_ptr当需要从多个地方管理对象时

注意: Java 的使用方式与 C++ 的使用方式之间的差异如此之大,我建议您忘记 Java 而你正在处理 C++。独立学习 C++ 作为一门新语言,而不必经常引用做事的“Java 方式”。

推荐书籍:The Definitive C++ Book Guide and List

关于java - 从 Java 到 C++ : how to use one custom class var within another custom class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187789/

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