You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类模板及模板模板参数函数实现出现语法错误问题求助

代码问题排查与修复

编译报错的核心语法问题

  • Complex类的赋值运算符operator=实现中,this为指针类型,不可使用.访问成员,需将this._re、this._im修改为this->_re、this->_im
  • Complex类的加法运算符operator+实现末尾,return temp缺少语句结束的分号,修改为return temp;

模板写法说明

你使用模板模板参数适配自定义模板类的写法是符合C标准的(要求C11及以上编译标准),无需调整。额外说明:你实现的第一个通用模板函数suma本身就支持所有重载了operator+的类型(包括你自定义的Complex模板类),如果没有特殊要求,可以不用单独编写适配模板模板参数的版本。

修复后完整代码

#include <iostream>

template <typename T>
class Complex
{
    T _re, _im;

public:
    Complex(T re = 0, T im = 0) :_re{re}, _im{im} {};
    ~Complex() {}
    Complex<T>& operator=(const Complex<T>& compl) { if (this == &compl) return *this; this->_re = compl._re; this->_im = compl._im; return *this; }
    Complex<T> operator+(const Complex<T>& compl) { Complex<T> temp; temp._re = _re + compl._re; temp._im = _im + compl._im; return temp; }
    // 已优化复数输出格式,你也可以保留原写法
    friend std::ostream& operator<<(std::ostream& os, const Complex<T>& compl) { os << compl._re << " + " << compl._im << "i"; return os; }
};

template <typename T>
T suma(T a, T b)
{
    return a + b;
}

template <template<typename> typename T, typename U>
void suma(T<U> a, T<U> b)
{
    T<U> temp = a + b;
    std::cout << temp;
}

int main()
{
    int a1{ 1 }, b1{ 3 };
    std::cout << "Suma de int : " << suma<int>(a1, b1) << std::endl;

    double a2{ 2.1 }, b2{ 5.9 };
    std::cout << "Suma de double: " << suma<double>(a2, b2) << std::endl;

    Complex<int> c1(3, 5), c2(8, 9);
    std::cout << "Suma comple int: ";
    suma<Complex, int>(c1, c2);
    // 也可以直接用通用模板写法,无需指定模板模板参数:
    // std::cout << "Suma comple int: " << suma(c1, c2) << std::endl;

    return 0;
}

内容的提问来源于stack exchange,提问作者Dragoș-George Gherasim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:36:04