繁体   English   中英

将 Java 转换为 C++:模板与泛型

[英]Converting Java to C++: Templates vs. Generics

我是一个 C++ 新手,试图将 Java 代码转换为 C++,但我认为我做错了什么。 Java代码如下:

class Container<T> {
    public T internal;
    public static Container lastInstance;
    Container(T value){
        internal = value;
        lastInstance = this;
    }
}

class test2 {
    public static void main(String argv[]){
        Container<String> str = new Container<String>("moo");
        Container<Integer> myint = new Container<Integer>(777);
        System.out.println("Last Instance: " + str.lastInstance.internal);
    }
}

到目前为止,我对 C++ 有以下几点:

#include <iostream>

using namespace std;

template <class T> class Container {
public:
  T internal;
  static Container<T> *lastInstance;

  Container(T val){
    internal = val;
    lastInstance = this;
  };
};

int main(){

  Container<int> *myint = new Container<int>(4);
  Container<string> *str = new Container<string>("hello");
  cout << myint->lastInstance->internal << endl;
  cout << str->lastInstance->internal << endl;

  return 0;
}

当我尝试编译时,我收到Undefined symbols for architecture x86_64:Undefined symbols for architecture x86_64:错误。 我究竟做错了什么?

编辑:有关错误的更多信息。 该错误确实是链接错误。 这是完整的消息:

Undefined symbols for architecture x86_64:
"Container<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::lastInstance", referenced from:
  _main in template-d68cfa.o
  Container<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::Container(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in template-d68cfa.o
"Container<int>::lastInstance", referenced from:
  _main in template-d68cfa.o
  Container<int>::Container(int) in template-d68cfa.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

EDIT2:使用 g++ 编译

一个前提:一般来说,比较Java泛型和C++模板就像比较苹果和橘子。 它们在语义上完全不同,并且以完全不同的方式工作。

因此,除非您知道它们为何不同以及如何不同,否则尝试将其翻译成另一种并不是一个好主意。

关于您的具体问题,这是因为您有一个static成员变量。 C++ 中的static成员变量需要在类声明之外定义,这是因为您必须告诉编译器此静态变量将存储在哪里。

所以基本上要解决你的问题,你需要添加lastInstance的定义:

template<typename T> Container<T>* Container<T>::lastInstance;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM