我是C ++的新手,试图学习C ++。我在Java中有这样的代码块:
public List<String> getDiagnosticTroubleCode() {
if (diagnosticTroubleCode == null) {
diagnosticTroubleCode = new ArrayList<String>();
}
return this.diagnosticTroubleCode;
}
如何比较disgnosticTroubleCode
与null
值?并将其设置为新的List
。我已经覆盖了std::list
以使其像Java中的List
一样使用。然后,我想返回对象diagnosticTroubleCode
中的this
字段。我希望你们能帮助我。试图研究this
指针和null
。
这是我在C ++中的头文件:
class RUNTIME_EXPORTS DiagnosticTroubleCode {
protected:
List diagnosticTroubleCode;
public:
List getDiagnosticTroubleCode();
};
您的代码似乎只希望在首次使用时实例化diagnosticTroubleCode
。坦白地说,我觉得有些奇怪,因为否则为空的std::list<std::string>
实例将是相当良性的。无论如何,这是一种实现方法。
class DiagnosticTroubleCode
{
protected:
std::unique_ptr<std::list<std::string>> diagnosticTroubleCode;
public:
std::list<std::string>& getDiagnosticTroubleCode()
{
if (!diagnosticTroubleCode)
diagnosticTroubleCode = std::make_unique<std::list<std::string>>();
return *diagnosticTroubleCode;
}
};
请注意,成员getDiagnosticTroubleCode
将返回对新(或现有)实例化列表的引用。如果您决定放弃潜在的实例化(我建议您这样做),代码将变得相当简单:
class DiagnosticTroubleCode
{
protected:
std::list<std::string> diagnosticTroubleCode;
public:
std::list<std::string>& getDiagnosticTroubleCode()
{
return diagnosticTroubleCode;
}
};
如果后者可行(坦率地说,我看不到它不可能),请首先进行。在上述两种情况下,成员都是通过引用而不是值或地址返回的。这与您可能熟悉的最相似。
祝你好运。
我记得在Java中,所有东西都是指针。因此,在Java中,diagnosticTroubleCode == null
本质上是将diagnosticTroubleCode
与空指针进行比较。在C ++中,我们没有null,我们有NULL
或nullptr
。在C ++中,对象不能真正为null,因为不是。对象在构造时会占用一块内存,因此它永远不能为null。因此,请尝试使自己熟悉指针,并利用它来发挥自己的优势。
关于this
。如果要返回成员变量,则不需要写return this.variable
,只需写return variable
就可以返回变量。
这里的区别在于,在Java中,所有复杂的结构声明实际上都是对这些结构的references的声明。在C ++中,这相当于说List& foo
或List* foo
。 C / C ++声明是真实的实例,这是内存管理可能会有些复杂的原因之一,但是它具有信息完整性的好处:例如,当您传递Java List<String>
作为参数时方法并更改该参数的内容,但在调用范围内已更改。另一方面,C / C ++会copy参数而不考虑对象的复杂性,并且当函数/方法返回时,将保留作为参数传递的参数。
您的C ++类示例应如下所示:
#include <list>
#include <string>
using namespace std;
class RUNTIME_EXPORTS DiagnosticTroubleCode {
protected:
list<string>* diagnosticTroubleCode{nullptr};
public:
list<string>* getDiagnosticTroubleCode();
};
list<string>* DiagnosticTroubleCode::getDiagnosticTroubleCode(){
if (diagnosticTroubleCode == nullptr) {
diagnosticTroubleCode = new List<string>();
}
return diagnosticTroubleCode;
}
[有更好的实现,不需要返回指针或引用,但是它们提出了额外的设计要求(例如,添加故障代码机制应该是什么。)>]
您可以使用类似这样的东西
我的.cpp文件: